package algorithms.sorting;

import java.util.Arrays;

public class BubbleSorting implements Sorter {
	private int[] workingList;

	@Override
	public int[] sort(int[] integersToSort) {
		if (integersToSort == null)
			throw new IllegalArgumentException();

		workingList = Arrays.copyOf(integersToSort, integersToSort.length);
		for (int j = 0; j < workingList.length; j++) {
			compareAllPairs();
		}

		return workingList;
	}

	private void compareAllPairs() {
		for (int i = 0; i < workingList.length - 1; i++) {
			if (shouldBeReplaced(i, i + 1)) {
				replaceElements(i, i + 1);
			}
		}
	}

	private boolean shouldBeReplaced(int index1, int index2) {
		return workingList[index1] > workingList[index2];
	}

	private void replaceElements(int index1, int index2) {
		int tmp = workingList[index1];
		workingList[index1] = workingList[index2];
		workingList[index2] = tmp;
	}
}
